﻿namespace TestTool.GUI.Utils
{
    using iTextSharp.text;
    using iTextSharp.text.pdf;
    using System;
    using System.IO;
    using System.Runtime.CompilerServices;
    using TestTool.GUI.Data;

    internal class PdfDocGenerator : IReportGenerator
    {
        private iTextSharp.text.Document _document;
        private TestLogFull _log;

        public event Action<Exception> OnException;

        public event Action OnReportSaved;

        public void CreateReport(string fileName, TestLogFull log)
        {
            this._log = log;
            bool flag = false;
            try
            {
                this._document = new iTextSharp.text.Document(PageSize.A4);
                this.Writer = PdfWriter.GetInstance(this._document, new FileStream(fileName, FileMode.Create));
                this.CustomDocumentInitialization();
                this._document.Open();
                this.GenerateDocumentContent();
                flag = true;
            }
            catch (Exception exception)
            {
                this.RaiseOnException(exception);
            }
            finally
            {
                if (this._document.IsOpen())
                {
                    this._document.Close();
                }
            }
            if (flag)
            {
                this.RaiseDocumentSaved();
            }
        }

        protected virtual void CustomDocumentInitialization()
        {
        }

        protected virtual void GenerateDocumentContent()
        {
        }

        protected void RaiseDocumentSaved()
        {
            if (this.OnReportSaved != null)
            {
                this.OnReportSaved();
            }
        }

        protected void RaiseOnException(Exception exc)
        {
            if (this.OnException != null)
            {
                this.OnException(exc);
            }
        }

        protected iTextSharp.text.Document Document
        {
            get
            {
                return this._document;
            }
        }

        protected TestLogFull Log
        {
            get
            {
                return this._log;
            }
        }

        protected PdfWriter Writer { get; private set; }
    }
}

